package signup.domain;

import java.util.List;


import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class UserFactory {
	static EntityManagerFactory emf =
        Persistence.createEntityManagerFactory("pu");
	
	@SuppressWarnings("unchecked")
	static public Users createUser(String name, String emailAddress, String phoneNumber, String password )
	{
		
		EntityManager jpa = emf.createEntityManager();
		List<Users> a=jpa.createQuery("from Users b where b.emailAddress=?").setParameter(1, emailAddress).getResultList();
	    if (a.size()>0)
	    {
	    	System.out.println("User already exist");
	    	return null;
	    }
	    
	    Users u=new Users(emailAddress,name,phoneNumber,password);
        EntityTransaction tx = jpa.getTransaction();
        try {
            tx.begin();
            jpa.persist(u);
            //jpa.persist(new Item("Another Item", "Cool"));
            tx.commit();
        } catch (Exception x) {
        	x.printStackTrace();
        	tx.rollback();
            return null;
        }
       	System.out.println("User created. ID"+ u.getUserId());
       	return u;
	}
	
	

}
